<template>
	<div class="q-pa-md seal-maintenance-page">
		<div class="page-header">
			<h4 class="page-title">印章维护</h4>
			<p class="page-description">选择部门并管理印章权限</p>
		</div>

		<q-card class="form-card">
			<q-card-section>
				<q-form @submit="onSubmit" class="q-gutter-lg">
					<q-select v-model="model" :options="options" label="选择部门" class="department-select"
						:loading="loading" emit-value map-options filled />

					<template v-if="yzoptions.length > 0">
						<div class="section-title">印章种类</div>
						<q-option-group v-model="yzzl" type="checkbox" :options="yzoptions"
							class="option-group horizontal-options" inline @update:model-value="onCheckboxChange" />

						<div class="section-title">选择印章</div>
						<q-option-group :options="xzyzzl" type="radio" v-model="xzyz"
							class="option-group horizontal-options" inline @update:model-value="onRadioChange" />
					</template>

					<div class="action-buttons">
						<q-btn label="搜索" type="submit" color="primary" :loading="loading" icon="search" />
						<q-btn label="重置" type="reset" color="grey" @click="resetForm" class="q-ml-sm" />
						<q-btn label="印章用途批量赋值" color="red" icon="search" @click="handleBatchAssign" class="q-ml-sm" />
						<q-btn label="将选中印章用途赋值给新印章" color="secondary" icon="search" @click="handleAssignToNewSeal"
							class="q-ml-sm" />
						<q-btn label="将选中印章新增用途" color="amber" icon="search" @click="handleAddSealUsage"
							class="q-ml-sm" />
						<q-btn label="新增无授权印章" style="background: #FF0080; color: white"
							@click="handleAddUnauthorizedSeal" class="q-ml-sm" />
					</div>
				</q-form>
			</q-card-section>
		</q-card>

		<!-- 印章使用记录表格 -->
		<q-card class="table-card q-mt-lg" v-if="tableData.length > 0">
			<q-card-section>
				<div class="table-header">
					<h5 class="table-title">印章使用记录</h5>
					<div class="table-description">共 {{ tableData.length }} 条记录</div>
				</div>

				<q-table :rows="tableData" :columns="columns" row-key="id" flat bordered :loading="tableLoading"
					class="seal-table" :rows-per-page-options="[10, 20, 50, 100]" :pagination="{ rowsPerPage: 50 }">
					<template v-slot:body-cell-yt="props">
						<q-td :props="props">
							<div v-if="!props.row.editing" class="usage-text" @dblclick="startEditing(props.row)">
								{{ props.row.yt }}
								<q-tooltip>双击编辑</q-tooltip>
							</div>
							<q-input v-else v-model="props.row.editedYt" type="textarea" autofocus :rows="3" dense
								filled @blur="saveEditing(props.row)" @keyup.enter="saveEditing(props.row)"
								@keyup.esc="cancelEditing(props.row)" class="usage-input" />
						</q-td>
					</template>

					<template v-slot:body-cell-actions="props">
						<q-td :props="props">
							<q-btn v-if="props.row.editing" icon="check" color="positive" size="sm"
								@click="saveEditing(props.row)" class="q-mr-xs">
								<q-tooltip>保存</q-tooltip>
							</q-btn>
							<q-btn v-if="props.row.editing" icon="close" color="negative" size="sm"
								@click="cancelEditing(props.row)" class="q-mr-xs">
								<q-tooltip>取消</q-tooltip>
							</q-btn>
							<q-btn v-else icon="edit" color="primary" size="sm" @click="startEditing(props.row)"
								class="q-mr-xs">
								<q-tooltip>编辑</q-tooltip>
							</q-btn>
							<q-btn icon="delete" color="negative" size="sm" @click="confirmDelete(props.row)">
								<q-tooltip>删除</q-tooltip>
							</q-btn>
						</q-td>
					</template>
				</q-table>
			</q-card-section>
		</q-card>

		<q-dialog v-model="fixed">
			<q-card style="min-width: 500px">
				<q-card-section>
					<h6 class="text-h6 q-my-none">新增无授权印章</h6>
				</q-card-section>

				<q-card-section class="q-pt-none">
					<q-form @submit="addUnauthorizedSeal" class="q-gutter-md">
						<q-input
							v-model="sealName"
							label="印章名称"
							filled
							:rules="[val => !!val || '印章名称不能为空']"
						/>
						<q-select
							v-model="keeper"
							:options="keeperOptions"
							label="保管人"
							filled
							use-input
							input-debounce="300"
							option-value="id"
							option-label="lastname"
							emit-value
							map-options
							@filter="filterKeepers"
							:rules="[val => !!val || '请选择保管人']"
						/>
					</q-form>
				</q-card-section>

				<q-card-actions align="right">
					<q-btn flat label="取消" color="primary" v-close-popup />
					<q-btn label="确定" color="primary" @click="addUnauthorizedSeal" />
				</q-card-actions>
			</q-card>
		</q-dialog>
	</div>
</template>

<script>
export default {
	data() {
		return {
			options: [
				{ label: '人力行政管理中心', value: '人力行政管理中心' },
				{ label: '物流管理中心', value: '物流管理中心' },
				{ label: '安全环境管理中心', value: '安全环境管理中心' },
				{ label: '财务管理中心', value: '财务管理中心' },
				{ label: '单证部', value: '单证部' },
				{ label: '信息发展管理中心', value: '信息发展管理中心' },
				{ label: '业务部门', value: '业务部门' }
			],
			model: null,
			yzzl: [],
			yzoptions: [],
			xzyzzl: [],
			xzyz: null,
			loading: false,
			tableData: [], // 存储表格数据
			tableLoading: false, // 表格加载状态
			columns: [ // 表格列配置
				{ name: 'id', label: 'ID', field: 'id', align: 'center', sortable: true },
				{ name: 'yzmc', label: '印章名称', field: 'yzmc', align: 'center' },
				{ name: 'bgr', label: '保管人', field: 'bgr', align: 'center' },
				{ name: 'yt', label: '用途', field: 'yt', align: 'left', sortable: true }, // 添加 sortable: true
				{ name: 'sqr', label: '申请人', field: 'sqr', align: 'center' },
				{ name: 'bm', label: '部门', field: 'bm', align: 'center' },
				{ name: 'lei', label: '类型', field: 'lei', align: 'center' },
				{ name: 'actions', label: '操作', align: 'center' }
			],
			fixed: false,
			sealName: '', // 新增：印章名称
			keeper: null, // 新增：保管人
			keeperOptions: [] // 新增：保管人选项
		};
	},
	methods: {
		async onSubmit() {
			if (this.model) {
				this.loading = true;
				try {
					const result = await this.$API.sealmaintenance.GetYZ.get(this.model);
					this.yzoptions = result.map(item => ({
						label: item,
						value: item
					}));
					this.xzyzzl = result.map(item => ({
						label: item,
						value: item
					}));
				} catch (error) {
					console.error('获取印章数据失败:', error);
					this.$q.notify({
						type: 'negative',
						message: '获取印章数据失败'
					});
				} finally {
					this.loading = false;
				}
			}
		},
		resetForm() {
			this.model = null;
			this.yzzl = [];
			this.yzoptions = [];
			this.xzyzzl = [];
			this.xzyz = null;
			this.tableData = []; // 清空表格数据
		},
		// 单选框点击事件
		onRadioChange(selectedValue) {
			this.$q.notify({
				type: 'positive',
				message: `已选择印章: ${selectedValue}`,
				timeout: 1000
			});
			this.handleSealSelection(selectedValue);
		},
		// 复选框点击事件
		onCheckboxChange(selectedValues) {
			this.$q.notify({
				type: 'info',
				message: `已选择 ${selectedValues.length} 种印章类型`,
				timeout: 1000
			});
			//this.handleSealTypeSelection(selectedValues);
		},
		// 处理印章选择业务逻辑
		async handleSealSelection(seal) {
			if (!this.model || !seal) return;

			this.tableLoading = true;
			try {
				const result = await this.$API.sealmaintenance.Getshouq.get(this.model, seal);
				// 为每条数据添加编辑状态
				this.tableData = result.map(item => ({
					...item,
					editing: false,
					editedYt: item.yt,
					originalYt: item.yt
				}));

				this.$q.notify({
					type: 'positive',
					message: `成功获取 ${result.length} 条使用记录`,
					timeout: 2000
				});
			} catch (error) {
				console.error('获取印章使用记录失败:', error);
				this.$q.notify({
					type: 'negative',
					message: '获取印章使用记录失败'
				});
				this.tableData = [];
			} finally {
				this.tableLoading = false;
			}
		},

		// 开始编辑
		startEditing(row) {
			row.editing = true;
			row.editedYt = row.yt;
			row.originalYt = row.yt;
		},

		// 保存编辑
		async saveEditing(row) {
			console.log('保存编辑:', row);
			if (row.editedYt !== row.originalYt) {
				row.yt = row.editedYt;
				this.$q.notify({
					type: 'positive',
					message: '用途已更新',
					timeout: 1000
				});

				// 这里可以添加API调用保存到后端
				// this.saveUsageToBackend(row.id, row.editedYt);
				await this.$API.sealmaintenance.SaveEditing.post(row);
			}
			row.editing = false;
		},

		// 取消编辑
		cancelEditing(row) {
			row.editedYt = row.originalYt;
			row.editing = false;
			this.$q.notify({
				type: 'info',
				message: '编辑已取消',
				timeout: 1000
			});
		},

		// 保存到后端API（示例）
		async saveUsageToBackend(id, newUsage) {
			try {
				await this.$API.sealmaintenance.UpdateUsage.update(id, newUsage);
			} catch (error) {
				console.error('保存用途失败:', error);
				this.$q.notify({
					type: 'negative',
					message: '保存失败'
				});
			}
		},
		// 确认删除
		confirmDelete(row) {
			this.$q.dialog({
				title: '确认删除',
				message: `确定要删除印章记录 "${row.yzmc}" 吗？`,
				cancel: true,
				persistent: true
			}).onOk(() => {
				this.deleteRow(row);
			});
		},

		// 删除行
		async deleteRow(row) {
			try {
				// 调用API删除后端数据
				console.log(row.id)
				await this.$API.sealmaintenance.DelEditing.delete(row.id);

				// 从前端表格中移除
				const index = this.tableData.findIndex(item => item.id === row.id);
				if (index !== -1) {
					this.tableData.splice(index, 1);
				}

				this.$q.notify({
					type: 'positive',
					message: '删除成功',
					timeout: 2000
				});
			} catch (error) {
				console.error('删除失败:', error);
				this.$q.notify({
					type: 'negative',
					message: '删除失败'
				});
			}
		},
		// 批量赋值
		async handleBatchAssign() {
			this.$q.dialog({
				title: '印章用途批量赋值',
				message: '确认批量赋值吗？',
				cancel: true,
				persistent: true
			}).onOk(async () => {
				// console.log(this.yzzl)
				// console.log(this.xzyz)
				// console.log(this.model)
				var ytfz = {
					bm: '',
					xzyz: '',
					fzyz: []
				}
				ytfz.bm = this.model;
				ytfz.xzyz = this.xzyz;
				ytfz.fzyz = this.yzzl;
				console.log(ytfz)
				await this.$API.sealmaintenance.fzyt.post(ytfz);
				this.$q.notify({
					type: 'positive',
					message: '批量赋值成功',
					timeout: 2000
				});
			});
		},
		// 将选中印章用途赋值给新印章
		async handleAssignToNewSeal() {
			this.$q.dialog({
				title: '将选中印章用途赋值给新印章',
				message: '请输入新印章名称（必填）',
				prompt: {
					model: '',
					type: 'text',
					isValid: val => val && val.trim().length > 0,
					errorMessage: '新印章名称不能为空'
				},
				cancel: true,
				persistent: true
			}).onOk(async (newSealName) => {
				if (!newSealName || newSealName.trim().length === 0) {
					this.$q.notify({
						type: 'negative',
						message: '新印章名称不能为空',
						timeout: 2000
					});
					return;
				}

				// 调用API将选中印章用途赋值给新印章
				try {
					// await this.$API.sealmaintenance.fzyt.post({
					// 	bm: this.model,
					// 	xzyz: this.xzyz,
					// 	fzyz: this.yzzl,
					// 	newSeal: newSealName.trim()
					// });
					var ytfz = {
						bm: '',
						xzyz: '',
						fzyz: ''
					}
					ytfz.bm = this.model;
					ytfz.xzyz = this.xzyz;
					ytfz.fzyz = newSealName.trim();
					console.log(ytfz);
					await this.$API.sealmaintenance.xzfzyt.post(ytfz);
					this.$q.notify({
						type: 'positive',
						message: '将选中印章用途赋值给新印章成功',
						timeout: 2000
					});
				} catch (error) {
					console.error('赋值失败:', error);
					this.$q.notify({
						type: 'negative',
						message: '赋值失败',
						timeout: 2000
					});
				}
			});
		},

		// 将选中印章新增用途
		async handleAddSealUsage() {
			this.$q.dialog({
				title: '将选中印章新增用途',
				message: '请输入新印章用途（必填）',
				prompt: {
					model: '',
					type: 'text',
					isValid: val => val && val.trim().length > 0,
					errorMessage: '新印章用途不能为空'
				},
				cancel: true,
				persistent: true
			}).onOk(async (newSealUsage) => {
				if (!newSealUsage || newSealUsage.trim().length === 0) {
					this.$q.notify({
						type: 'negative',
						message: '新印章用途不能为空',
						timeout: 2000
					});
					return;
				} else {
					var ytfz = {
						bm: '',
						xzyz: '',
						yt: newSealUsage.trim()
					}
					ytfz.bm = this.model;
					ytfz.xzyz = this.xzyz;
					console.log(ytfz)
					await this.$API.sealmaintenance.xzyt.post(ytfz);
					this.$q.notify({
						type: 'positive',
						message: '将选中印章新增用途成功',
						timeout: 2000
					});
				}
			})
		},
		async handleAddUnauthorizedSeal() {
			this.fixed = true;
			// 打开对话框时获取保管人列表
			await this.getKeeperOptions();
		},

		// 获取保管人选项
		async getKeeperOptions() {
			try {
				const result = await this.$API.sealmaintenance.Getry.get();
				console.log(result)
				this.keeperOptions = result;
			} catch (error) {
				console.error('获取保管人列表失败:', error);
				this.$q.notify({
					type: 'negative',
					message: '获取保管人列表失败'
				});
			}
		},

		// 保管人筛选
		filterKeepers(val, update) {
			if (val === '') {
				update(() => {
					// eslint-disable-next-line no-self-assign
					this.keeperOptions = this.keeperOptions;
				});
				return;
			}

			update(() => {
					const needle = val.toLowerCase();
					this.keeperOptions = this.keeperOptions.filter(
						v => v.lastname.toLowerCase().indexOf(needle) > -1
					);
				});
		},

		// 新增无授权印章
		// 新增无授权印章
		async addUnauthorizedSeal() {
				if (!this.sealName || !this.keeper) {
					this.$q.notify({
						type: 'negative',
						message: '请填写印章名称并选择保管人'
					});
					return;
				}

				try {
					// 将保管人的id传给后台
					// await this.$API.sealmaintenance.AddUnauthorizedSeal.post({
					// 	sealName: this.sealName,
					// 	keeperId: this.keeper // 这里传递的是保管人的id
					// });
					console.log(this.sealName)
					console.log(this.keeper)
					var a= await this.$API.sealmaintenance.Addwu.post(this.keeper,this.sealName);
					this.$q.notify({
						type: 'positive',
						message: a
					});

					this.fixed = false;
					this.sealName = '';
					this.keeper = null;
				} catch (error) {
					console.error('新增无授权印章失败:', error);
					this.$q.notify({
						type: 'negative',
						message: '新增无授权印章失败'
					});
				}
			}
	},
}
</script>

<style lang="scss" scoped>
.seal-maintenance-page {
	max-width: 1200px;
	margin: 0 auto;

	.page-header {
		text-align: center;
		margin-bottom: 30px;

		.page-title {
			font-size: 24px;
			font-weight: bold;
			color: #2c3e50;
			margin-bottom: 8px;
		}
		.page-description {
			font-size: 14px;
			color: #7f8c8d;
		}
	}

	.form-card {
		box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);
		border-radius: 12px;

		.department-select {
			max-width: 400px;
			margin-bottom: 24px;
		}

		.section-title {
			font-size: 16px;
			font-weight: 600;
			color: #34495e;
			margin: 20px 0 12px 0;
			padding-left: 4px;
			border-left: 4px solid #3498db;
		}

		.option-group {
			margin: 16px 0;
		}

		.horizontal-options {
			::v-deep .q-option {
				display: inline-flex;
				margin-right: 20px;
				margin-bottom: 10px;
			}

			::v-deep .q-radio__inner {
				margin-right: 8px;
			}

			::v-deep .q-checkbox__inner {
				margin-right: 8px;
			}
		}

		.action-buttons {
			margin-top: 32px;
			padding-top: 20px;
			border-top: 1px solid #eee;
			text-align: center;
		}
	}

	// 表格卡片样式
	.table-card {
		box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);
		border-radius: 12px;

		.table-header {
			margin-bottom: 20px;

			.table-title {
				font-size: 18px;
				font-weight: 600;
				color: #2c3e50;
				margin: 0;
			}

			.table-description {
				font-size: 14px;
				color: #7f8c8d;
				margin-top: 4px;
			}
		}

		.seal-table {
			::v-deep .q-table__top {
				padding: 0;
			}

			::v-deep .q-table thead tr {
				background-color: #f8f9fa;
			}

			::v-deep .q-table th {
				font-weight: 600;
				color: #2c3e50;
			}

			.usage-text {
				max-width: 300px;
				word-wrap: break-word;
				white-space: normal;
				line-height: 1.4;
				cursor: pointer;
				padding: 8px;
				border-radius: 4px;
				transition: background-color 0.2s;

				&:hover {
					background-color: #f0f8ff;
				}
			}

			.usage-input {
				max-width: 300px;

				::v-deep .q-field__control {
					min-height: 80px;
				}
			}
		}
	}
}

// 响应式设计
@media (max-width: 600px) {
	.seal-maintenance-page {
		padding: 16px;

		.form-card {
			margin: 0 -16px;
			border-radius: 0;
			box-shadow: none;

			::v-deep .q-card__section {
				padding: 20px 16px;
			}

			.horizontal-options {
				::v-deep .q-option {
					display: block;
					margin-right: 0;
					margin-bottom: 8px;
				}
			}
		}

		.table-card {
			margin: 0 -16px;
			border-radius: 0;
			box-shadow: none;

			::v-deep .q-table {
				font-size: 12px;
			}

			.usage-text {
				max-width: 200px;
				font-size: 12px;
			}
		}
	}
}
</style>